﻿using System;
using System.Collections.Generic;
using BigfootSQL.Validation;

namespace BigfootSQL
{
    public abstract class BaseModel
    {
        private Validator _validate;
        public abstract void ExecuteValidation();
        
        public Validator Validate
        {
            get { return _validate ?? (_validate = new Validator()); }
        }
        
        public bool IsValid() { return IsValid(false); }
        
        public bool IsValid(bool throwException)
        {
            ExecuteValidation();
            var hasErrors = Validate.HasErrors();
            if (hasErrors && throwException) throw GetErrorsAsException();
            return hasErrors;
        }

        public List<ModelError> GetErrors()
        {
            ExecuteValidation();
            var errors = new List<ModelError>();
            foreach (var er in _validate.ValidatorResults)
            {
                errors.Add(new ModelError(er.FieldName, er.ValidationMessage));
            }
            return errors; 
        }

        public Exception GetErrorsAsException()
        {
            ExecuteValidation();
            var errors = GetErrors();
            var message = "";
            foreach (var er in errors)
            {
                if (message.Length > 0) message += " | ";
                message += er.Message;
            }
            return new Exception(message);
        }

    }
}
